import { NextRequest, NextResponse } from 'next/server';
import sqlite3 from 'sqlite3';
import path from 'path';
import { getDatabasePath } from '@/lib/database-path';

const dbPath = getDatabasePath();

interface ContactInfo {
  id: string;
  type: 'wechat_group' | 'wechat_official' | 'qq_group' | 'email' | 'phone' | 'address';
  title: string;
  description?: string;
  content: string;
  qrCode?: string;
  isVisible: boolean;
  order: number;
}

// 初始化数据库表
const initializeDatabase = () => {
  return new Promise<sqlite3.Database>((resolve, reject) => {
    const db = new sqlite3.Database(dbPath, (err) => {
      if (err) {
        reject(err);
        return;
      }
      
      // 创建联系方式表
      db.run(`CREATE TABLE IF NOT EXISTS contacts (
        id TEXT PRIMARY KEY,
        type TEXT NOT NULL,
        title TEXT NOT NULL,
        description TEXT,
        content TEXT NOT NULL,
        qr_code TEXT,
        is_visible INTEGER DEFAULT 1,
        order_num INTEGER DEFAULT 1,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )`, (err) => {
        if (err) {
          reject(err);
          return;
        }
        
        // 检查是否有数据，如果没有就插入测试数据
        db.get('SELECT COUNT(*) as count FROM contacts', (err, row: any) => {
          if (!err && row.count === 0) {
            console.log('🔄 插入初始联系方式数据...');
            
            const defaultContacts = [
              {
                id: 'wechat-group-init',
                type: 'wechat_group',
                title: '技术交流群',
                description: '讨论机器人技术，分享学习资源',
                content: '扫码加入微信群',
                qr_code: '/uploads/wechat-group-qr.svg',
                is_visible: 1,
                order_num: 1
              },
              {
                id: 'email-init',
                type: 'email', 
                title: '联系邮箱',
                description: '商务合作、学术交流',
                content: 'contact@roboticslab.com',
                qr_code: null,
                is_visible: 1,
                order_num: 2
              }
            ];
            
            const stmt = db.prepare(`INSERT INTO contacts (id, type, title, description, content, qr_code, is_visible, order_num) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);
            
            defaultContacts.forEach(contact => {
              stmt.run([
                contact.id, 
                contact.type, 
                contact.title, 
                contact.description, 
                contact.content, 
                contact.qr_code, 
                contact.is_visible, 
                contact.order_num
              ]);
            });
            
            stmt.finalize(() => {
              console.log('✅ 初始联系方式数据已插入');
              resolve(db);
            });
          } else {
            resolve(db);
          }
        });
      });
    });
  });
};

export async function GET(request: NextRequest) {
  try {
    console.log('后台API: 数据库路径 =', dbPath);
    const db = await initializeDatabase();
    
    return new Promise<NextResponse>((resolve, reject) => {
      db.all(`
        SELECT id, type, title, description, content, qr_code as qrCode, is_visible as isVisible, order_num as orderNum
        FROM contacts 
        ORDER BY order_num ASC
      `, (err, rows: any[]) => {
        db.close();
        
        if (err) {
          reject(err);
          return;
        }
        
        const contacts: ContactInfo[] = rows.map(row => ({
          id: row.id,
          type: row.type,
          title: row.title,
          description: row.description,
          content: row.content,
          qrCode: row.qrCode,
          isVisible: Boolean(row.isVisible),
          order: row.orderNum
        }));
        
        resolve(NextResponse.json({
          success: true,
          data: contacts
        }));
      });
    });
  } catch (error) {
    console.error('获取联系方式失败:', error);
    return NextResponse.json(
      { success: false, error: '获取联系方式失败' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const db = await initializeDatabase();
    const body = await request.json();
    
    const { type, title, description, content, qrCode, isVisible, order } = body;
    const id = Date.now().toString();
    
    return new Promise<NextResponse>((resolve, reject) => {
      db.run(`
        INSERT INTO contacts (id, type, title, description, content, qr_code, is_visible, order_num) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
      `, [id, type, title, description || null, content, qrCode || null, isVisible ? 1 : 0, order], function(err) {
        db.close();
        
        if (err) {
          reject(err);
          return;
        }
        
        resolve(NextResponse.json({
          success: true,
          data: { id, ...body }
        }));
      });
    });
  } catch (error) {
    console.error('创建联系方式失败:', error);
    return NextResponse.json(
      { success: false, error: '创建联系方式失败' },
      { status: 500 }
    );
  }
}

export async function PUT(request: NextRequest) {
  try {
    console.log('后台API PUT: 数据库路径 =', dbPath);
    const db = await initializeDatabase();
    const body = await request.json();
    
    const { id, type, title, description, content, qrCode, isVisible, order } = body;
    console.log('后台API PUT: 更新数据 =', { id, type, title, description, content, qrCode, isVisible, order });
    
    return new Promise<NextResponse>((resolve, reject) => {
      const sql = `
        UPDATE contacts 
        SET type = ?, title = ?, description = ?, content = ?, qr_code = ?, is_visible = ?, order_num = ?, updated_at = CURRENT_TIMESTAMP
        WHERE id = ?
      `;
      const params = [type, title, description || null, content, qrCode || null, isVisible ? 1 : 0, order, id];
      
      console.log('后台API PUT: 执行SQL =', sql);
      console.log('后台API PUT: 参数 =', params);
      
      db.run(sql, params, function(err) {
        if (err) {
          console.error('后台API PUT: SQL执行失败:', err);
          db.close();
          reject(err);
          return;
        }
        
        console.log('后台API PUT: SQL执行成功, 影响行数:', this.changes);
        console.log('后台API PUT: lastID:', this.lastID);
        
        db.close();
        
        resolve(NextResponse.json({
          success: true,
          data: body
        }));
      });
    });
  } catch (error) {
    console.error('更新联系方式失败:', error);
    return NextResponse.json(
      { success: false, error: '更新联系方式失败' },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  try {
    const db = await initializeDatabase();
    const { searchParams } = new URL(request.url);
    const id = searchParams.get('id');
    
    if (!id) {
      return NextResponse.json({ success: false, error: '缺少ID参数' }, { status: 400 });
    }
    
    return new Promise<NextResponse>((resolve, reject) => {
      db.run(`DELETE FROM contacts WHERE id = ?`, [id], function(err) {
        db.close();
        
        if (err) {
          reject(err);
          return;
        }
        
        resolve(NextResponse.json({
          success: true,
          message: '联系方式已删除'
        }));
      });
    });
  } catch (error) {
    console.error('删除联系方式失败:', error);
    return NextResponse.json(
      { success: false, error: '删除联系方式失败' },
      { status: 500 }
    );
  }
}